// 用户数据接口模拟
import { MockMethod } from 'vite-plugin-mock'

const userData = [
    {
        "id": 1,
        "name": "李斯",
        "age": 20,
        "position": "丞相",
        "addTime": new Date()
    },
    {
        "id": 2,
        "name": "嬴政",
        "age": 12,
        "position": "始皇帝",
        "addTime": new Date()
    },
    {
        "id": 3,
        "name": "吕不韦",
        "age": 50,
        "position": "商人",
        "addTime": new Date()
    }
]

export default [
    {
        url: '/api/users',
        method: 'get',
        timeout: 500,
        response: {
            code: 200,
            mes: '获取用户列表数据成功!',
            data: userData
        }
    },
    {
        url: '/api/users',
        method: 'post',
        timeout: 50,
        response: ({ body }:{body:any}) => {
            if (body) {
                if(userData.findIndex(item => item.name === body.name) !=  -1){
                    return {
                        code: 300,
                        mes: '该用户名已经添加!'
                    }
                }
                userData.push(body)
                return {
                    code: 200,
                    mes: '添加成功!'
                };
            }
            return {
                code: 500,
                mes: '添加失败请稍后再试!'
            };
        }
    },
    {
        url: '/api/users',
        method: 'delete',
        timeout: 50,
        response: ({ body }:{body:any}) => {
            if (body.id){
                // 单个删除
                const index = userData.findIndex(item => item.id == body.id)
                userData.splice(index,1)
                return {
                    code: 200,
                    mes: '删除成功!'
                };
            } else if (body.ids) {
                // 批量删除
                body.ids.forEach((id:any) => {
                    const index = userData.findIndex(item => item.id == id)
                    userData.splice(index,1)
                })
                return {
                    code: 200,
                    mes: '删除成功!'
                };
            }
            return {
                code: 100,
                mes: '删除失败，请稍后在试！'
            }}
    },
    {
        url: '/api/users',
        method: 'put',
        timeout: 50,
        response: ({ body }:{body:any}) => {
            if (body){
                const index = userData.findIndex(item => item.id == body.id)
                userData[index] = body
                return {
                    code: 200,
                    mes: '修改成功!'
                };
            }
            return {
                code: 100,
                mes: '修改失败，请稍后在试！'
            }}
    },
] as MockMethod[]
